<template>
  <div class="main">
    <el-scrollbar>
      <MainHeader />
      <div class="profile-edit">
        <div style="width: 60%; display: inline-block; min-width: 1000px;">
          <div class="profile-edit-main">
            <div class="profile-edit-avatar">
              <el-upload class="avatar-uploader" action="http://120.25.227.191:8080/user/upload/avatar"
                :data="{ id: user.id }" name="file" :headers="{
                  Authorization: token,
                }" :on-success="handleAvatarSuccess" :show-file-list="false" accept="jpg,jpeg,png"
                :before-upload="beforeUpload">
                <el-avatar :src="user.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'"
                  :size="180"></el-avatar>
                <i class="el-icon-camera-solid avatar-uploader-icon"></i>
              </el-upload>
            </div>
            <div class="profile-edit-text">
              <div class="profile-edit-text-basic">
                <el-tabs type="card">
                  <el-tab-pane label="基本信息">
                    <div class="profile-edit-text-basic-item">
                      <span class="profile-edit-text-basic-item-title">用户名</span>
                      <div v-if="isEditing.username === false">
                        <h3 style="margin-left: 5px;">{{ user.username }}&nbsp;&nbsp;<i class="el-icon-edit edit-option"
                            @click="() => { isEditing.username = true; temp.username = user.username }"></i></h3>
                      </div>
                      <div v-else>
                        <el-input v-model="temp.username" placeholder="请输入用户名"></el-input>
                        <div style="margin-top: 10px">
                          <el-button type="primary" size="small" @click="saveUsername"><i
                              class="el-icon-check"></i>&nbsp;&nbsp;保存</el-button>
                          <el-button type="plain" size="small" @click="cancelUsername"><i
                              class="el-icon-close"></i>&nbsp;&nbsp;取消</el-button>
                        </div>
                      </div>
                    </div>
                    <el-divider></el-divider>
                    <div class="profile-edit-text-basic-item">
                      <span class="profile-edit-text-basic-item-title">个性签名</span>
                      <div v-if="isEditing.description === false">
                        <h3 style="margin-left: 5px;">{{ user.description }}&nbsp;&nbsp;<i
                            class="el-icon-edit edit-option"
                            @click="() => { isEditing.description = true; temp.description = user.description }"></i>
                        </h3>
                      </div>
                      <div v-else>
                        <el-input v-model="temp.description" placeholder="请输入个性签名"></el-input>
                        <div style="margin-top: 10px">
                          <el-button type="primary" size="small" @click="saveDescription"><i
                              class="el-icon-check"></i>&nbsp;&nbsp;保存</el-button>
                          <el-button type="plain" size="small" @click="cancelDescription"><i
                              class="el-icon-close"></i>&nbsp;&nbsp;取消</el-button>
                        </div>
                      </div>
                    </div>
                    <el-divider></el-divider>
                    <div class="profile-edit-text-basic-item">
                      <span class="profile-edit-text-basic-item-title">学历</span>
                      <div v-if="isEditing.education === false">
                        <h3 style="margin-left: 5px;">{{ user.education }}&nbsp;&nbsp;<i
                            class="el-icon-edit edit-option"
                            @click="() => { isEditing.education = true; temp.education = user.education }"></i></h3>
                      </div>
                      <div v-else>
                        <el-select v-model="temp.education" placeholder="请选择">
                          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.label">
                          </el-option>
                        </el-select>
                        <div style="margin-top: 10px">
                          <el-button type="primary" size="small" @click="saveEducation"><i
                              class="el-icon-check"></i>&nbsp;&nbsp;保存</el-button>
                          <el-button type="plain" size="small" @click="cancelEducation"><i
                              class="el-icon-close"></i>&nbsp;&nbsp;取消</el-button>
                        </div>
                      </div>
                    </div>
                    <el-divider></el-divider>
                    <div class="profile-edit-text-basic-item">
                      <span class="profile-edit-text-basic-item-title">兴趣标签</span>
                      <div v-if="isEditing.tags === false">
                        <el-tag :key="tag" v-for="tag in user.tags">{{ tag }}</el-tag>&nbsp;&nbsp;<i
                          class="el-icon-edit edit-option"
                          @click="() => { isEditing.tags = true; temp.tags = user.tags }"></i>
                      </div>
                      <div v-else>
                        <el-tag :key="tag" v-for="tag in temp.tags" closable :disable-transitions="false"
                          @close="handleClose(tag)">
                          {{ tag }}
                        </el-tag>
                        <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput"
                          size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
                        <div style="margin-top: 10px">
                          <el-button type="primary" size="small" @click="saveTags"><i
                              class="el-icon-check"></i>&nbsp;&nbsp;保存</el-button>
                          <el-button type="plain" size="small" @click="cancelTags"><i
                              class="el-icon-close"></i>&nbsp;&nbsp;取消</el-button>
                        </div>
                      </div>
                    </div>
                    <el-divider></el-divider>
                  </el-tab-pane>
                  <el-tab-pane label="账户信息">
                    <div class="profile-edit-text-basic-item">
                      <span class="profile-edit-text-basic-item-title">邮箱</span>
                      <div v-if="isEditing.email === false">
                        <h3 style="margin-left: 5px;">{{ user.email }}&nbsp;&nbsp;<i class="el-icon-edit edit-option"
                            @click="() => { isEditing.email = true; emailForm.email = user.email }"></i></h3>
                      </div>
                      <div v-else>
                        <el-form :rules="emailRules" :model="emailForm" ref="emailForm">
                          <el-form-item v-if="!emailForm.inputAccess" prop="verifycode">
                            <el-input v-model="emailForm.verifycode" placeholder="请输入验证码"></el-input>
                            <div style="margin-top: 10px">
                              <el-button type="success" size="small" @click="sendCode('email')"
                                :disabled="emailForm.disabled">{{ emailForm.buttonName }}</el-button>
                              <el-button type="primary" size="small" @click="verify('email')">验证</el-button>
                              <el-button type="plain" size="small" @click="cancelEmail">取消</el-button>
                            </div>
                          </el-form-item>
                          <el-form-item v-else prop="email">
                            <el-input v-model="emailForm.email" placeholder="请输入邮箱"></el-input>
                            <div style="margin-top: 10px">
                              <el-button type="primary" size="small" @click="saveEmail"><i
                                  class="el-icon-check"></i>&nbsp;&nbsp;保存</el-button>
                              <el-button type="plain" size="small" @click="cancelEmail"><i
                                  class="el-icon-close"></i>&nbsp;&nbsp;取消</el-button>
                            </div>
                          </el-form-item>
                        </el-form>
                      </div>
                    </div>
                    <el-divider></el-divider>
                    <div class="profile-edit-text-basic-item">
                      <span class="profile-edit-text-basic-item-title">密码</span>
                      <div v-if="isEditing.password">
                        <el-form :rules="passwordRules" :model="passwordForm" ref="passwordForm">
                          <el-form-item v-if="!passwordForm.inputAccess" prop="verifycode">
                            <el-input v-model="passwordForm.verifycode" placeholder="请输入验证码"></el-input>
                            <div style="margin-top: 10px">
                              <el-button type="success" size="small" @click="sendCode('password')"
                                :disabled="passwordForm.disabled">{{ passwordForm.buttonName }}</el-button>
                              <el-button type="primary" size="small" @click="verify('password')">验证</el-button>
                              <el-button type="plain" size="small" @click="cancelPassword">取消</el-button>
                            </div>
                          </el-form-item>
                          <el-form-item v-if="passwordForm.inputAccess" prop="oldpassword">
                            <el-input v-model="passwordForm.oldpassword" placeholder="请输入旧密码" type="password">
                            </el-input>
                          </el-form-item>
                          <el-form-item v-if="passwordForm.inputAccess" prop="newpassword">
                            <el-input v-model="passwordForm.newpassword" placeholder="请输入新密码" type="password">
                            </el-input>
                          </el-form-item>
                          <el-form-item v-if="passwordForm.inputAccess" prop="confirmpassword">
                            <el-input v-model="passwordForm.confirmpassword" placeholder="请再次输入新密码" type="password">
                            </el-input>
                          </el-form-item>
                          <div v-if="passwordForm.inputAccess" style="margin-top: 10px">
                            <el-button type="primary" size="small" @click="savePassword"><i
                                class="el-icon-check"></i>&nbsp;&nbsp;保存</el-button>
                            <el-button type="plain" size="small" @click="cancelPassword"><i
                                class="el-icon-close"></i>&nbsp;&nbsp;取消</el-button>
                          </div>
                        </el-form>
                      </div>
                      <div v-else>
                        <h3 style="margin-left: 5px;">********&nbsp;&nbsp;<i class="el-icon-edit edit-option"
                            @click="isEditing.password = true"></i></h3>
                      </div>
                    </div>
                    <el-divider></el-divider>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script>
import MainHeader from '../components/MainHeader.vue';
import request from '@/API/request';
import { Message } from 'element-ui';

export default {
  data() {
    return {
      isEditing: {
        username: false,
        description: false,
        education: false,
        tags: false,
        email: false,
        password: false
      },
      temp: {
        username: '',
        description: '',
        education: '',
        tags: [],
      },
      emailForm: {
        email: '',
        verifycode: '',
        inputAccess: false,
        disabled: false,
        buttonName: '发送验证码',
        count: 60
      },
      passwordForm: {
        verifycode: '',
        inputAccess: false,
        oldpassword: '',
        newpassword: '',
        confirmpassword: '',
        disabled: false,
        buttonName: '发送验证码',
        count: 60
      },
      emailRules: {
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },
      passwordRules: {
        verifycode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ],
        oldpassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        newpassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 8, message: '密码长度不能小于8位', trigger: 'blur' }
        ],
        confirmpassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.passwordForm.newpassword) {
                callback(new Error('两次输入密码不一致!'));
              } else {
                callback();
              }
            }, trigger: 'blur'
          }
        ]
      },
      inputVisible: false,
      inputValue: '',
      options: [
        { label: '博士毕业', value: '001' },
        { label: '博士在读', value: '002' },
        { label: '硕士毕业', value: '003' },
        { label: '硕士在读', value: '004' },
        { label: '本科毕业', value: '005' },
        { label: '本科在读', value: '006' },
        { label: '大专毕业', value: '007' },
        { label: '大专在读', value: '008' },
        { label: '高中毕业', value: '009' },
        { label: '高中在读', value: '010' },
        { label: '初中毕业', value: '011' },
        { label: '初中在读', value: '012' },
        { label: '小学及以下', value: '013' },
      ],
      verifyCode: '',
    };
  },
  computed: {
    user() {
      return this.$store.state.userInfo;
    },
    token() {
      return this.$store.state.token;
    }
  },
  methods: {
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        this.$store.commit('update', { key: 'avatar', value: res.data });
        Message({
          message: '头像修改成功',
          type: 'success',
          customClass: 'message-global'
        });
      } else {
        Message({
          message: res.msg,
          type: 'error',
          customClass: 'message-global'
        });
      }
    },

    beforeUpload(file) {
      const isJPEG = file.type === 'image/jpeg';
      const isJPG = file.type === 'image/jpg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG && !isJPEG) {
        Message({
          message: '上传头像图片只能是 JPG/PNG/JPEG 格式!',
          type: 'error',
          customClass: 'message-global'
        });
      }
      if (!isLt2M) {
        Message({
          message: '上传头像图片大小不能超过 2MB!',
          type: 'error',
          customClass: 'message-global'
        });
      }
      return (isJPG || isPNG || isJPEG) && isLt2M;
    },

    emailTimer() {
      var timeout = setInterval(() => {
        if (this.emailForm.count < 1) {
          this.emailForm.disabled = false;
          this.emailForm.buttonName = "发送验证码";
          this.emailForm.count = 60;
          clearInterval(timeout);
        } else {
          this.emailForm.disabled = true;
          this.emailForm.buttonName = this.emailForm.count-- + "s后重发";
        }
      }, 1000);
    },

    passwordTimer() {
      var timeout = setInterval(() => {
        if (this.passwordForm.count < 1) {
          this.passwordForm.disabled = false;
          this.passwordForm.buttonName = "发送验证码";
          this.passwordForm.count = 60;
          clearInterval(timeout);
        } else {
          this.passwordForm.disabled = true;
          this.passwordForm.buttonName = this.passwordForm.count-- + "s后重发";
        }
      }, 1000);
    },

    verify(type) {
      if (type === 'email') {
        if (this.emailForm.verifycode === '') {
          Message({
            message: '请输入验证码',
            type: 'error',
            customClass: 'message-global'
          });
        } else if (this.emailForm.verifycode == this.verifyCode) {
          this.emailForm.inputAccess = true;
          this.verifyCode = '';
          this.emailForm.verifycode = '';
          Message({
            message: '验证码正确',
            type: 'success',
            customClass: 'message-global'
          });
        } else {
          Message({
            message: '验证码错误',
            type: 'error',
            customClass: 'message-global'
          });
        }
      } else {
        if (this.passwordForm.verifycode === '') {
          Message({
            message: '请输入验证码',
            type: 'error',
            customClass: 'message-global'
          });
        } else if (this.passwordForm.verifycode == this.verifyCode) {
          this.passwordForm.inputAccess = true;
          this.verifyCode = '';
          this.passwordForm.verifycode = '';
          Message({
            message: '验证码正确',
            type: 'success',
            customClass: 'message-global'
          });
        } else {
          Message({
            message: '验证码错误',
            type: 'error',
            customClass: 'message-global'
          });
        }
      }
    },

    sendCode(type) {
      Message({
        message: '验证码已发送至邮箱',
        type: 'success',
        customClass: 'message-global'
      });
      if (type === 'email') {
        this.emailTimer();
      } else {
        this.passwordTimer();
      }
      request.get(
        '/user/sendIC',
        {
          timeout: 15000,
          params: {
            mail: this.user.email
          }
        }
      ).then(res => {
        if (res.data.code === 200) {
          this.verifyCode = res.data.data;
        } else {
          Message.error(res.data.msg);
        }
      });
    },
    saveUsername() {
      let rex = new RegExp('^[ ]+$')
      if (this.temp.username === '' || rex.test(this.temp.username)) {
        this.temp.username = '';
        this.isEditing.username = false;
      } else {
        this.$store.commit('update', { key: 'username', value: this.temp.username });
        request.post(
          '/user/update',
          {
            id: this.user.id,
            updateAttribute:
              { username: this.temp.username }
          },
        ).then(res => {
          if (res.data.code === 200) {
            Message.success('修改成功');
            this.isEditing.username = false;
          } else {
            Message.error('修改失败');
          }
        }).catch(err => {
          Message.error(err);
        });
      }
    },
    cancelUsername() {
      this.temp.username = '';
      this.isEditing.username = false;
    },
    saveDescription() {
      if (this.temp.description === '') {
        this.temp.description = '';
        this.isEditing.description = false;
      } else {
        this.$store.commit('update', { key: 'description', value: this.temp.description });
        request.post(
          '/user/update',
          {
            id: this.user.id,
            updateAttribute:
              { description: this.temp.description }
          },
        ).then(res => {
          if (res.data.code === 200) {
            Message.success('修改成功');
            this.isEditing.description = false;
          } else {
            Message.error('修改失败');
          }
        }).catch(err => {
          Message.error(err);
        });
      }
    },
    cancelDescription() {
      this.temp.description = '';
      this.isEditing.description = false;
    },
    saveEducation() {
      if (this.temp.education === '') {
        this.temp.education = '';
        this.isEditing.education = false;
      } else {
        this.$store.commit('update', { key: 'education', value: this.temp.education });
        request.post(
          '/user/update',
          {
            id: this.user.id,
            updateAttribute:
              { education: this.temp.education }
          },
        ).then(res => {
          if (res.data.code === 200) {
            Message.success('修改成功');
            this.isEditing.education = false;
          } else {
            Message.error('修改失败');
          }
        }).catch(err => {
          Message.error(err);
        });
      }
    },
    cancelEducation() {
      this.temp.education = '';
      this.isEditing.education = false;
    },
    saveTags() {
      if (this.temp.tags.length === 0) {
        this.temp.tags = [];
        this.isEditing.tags = false;
      } else {
        this.$store.commit('update', { key: 'tags', value: this.temp.tags });
        request.post(
          '/user/update',
          {
            id: this.user.id,
            updateAttribute:
              { tags: this.temp.tags }
          },
        ).then(res => {
          if (res.data.code === 200) {
            Message.success('修改成功');
            this.isEditing.tags = false;
          } else {
            Message.error('修改失败');
          }
        }).catch(err => {
          Message.error(err);
        });
      }
    },
    cancelTags() {
      this.temp.tags = [];
      this.isEditing.tags = false;
    },
    saveEmail() {
      if (this.emailForm.email === '') {
        this.emailForm.email = '';
        this.emailForm.inputAccess = false;
        this.isEditing.email = false;
        this.emailForm.verifycode = '';
      } else {
        this.$store.commit('update', { key: 'email', value: this.emailForm.email });
        request.post(
          '/user/update',
          {
            id: this.user.id,
            updateAttribute:
              { email: this.emailForm.email }
          },
        ).then(res => {
          if (res.data.code === 200) {
            Message({
              message: '修改成功',
              type: 'success',
              customClass: 'message-global'
            });
            this.emailForm.email = '';
            this.emailForm.inputAccess = false;
            this.isEditing.email = false;
            this.verifyCode = '';
          } else {
            Message({
              message: res.data.msg,
              type: 'error',
              customClass: 'message-global'
            });
          }
        }).catch(err => {
          Message(
            {
              message: err,
              type: 'error',
              customClass: 'message-global'
            }
          );
        });
      }
    },
    cancelEmail() {
      this.emailForm.verifycode = '';
      this.emailForm.email = '';
      this.isEditing.email = false;
      this.emailForm.inputAccess = false;
    },
    savePassword() {
      if (this.passwordForm.oldpassword === '') {
        Message({
          message: '请输入旧密码',
          type: 'warning',
          customClass: 'message-global'
        });
      } else if (this.passwordForm.newpassword === '') {
        this.passwordForm.verifycode = '';
        this.passwordForm.oldpassword = '';
        this.passwordForm.newpassword = '';
        this.passwordForm.confirmpassword = '';
        this.passwordForm.inputAccess = false;
        this.isEditing.password = false;
      } else {
        request.post(
          '/user/change/password',
          {
            id: this.user.id,
            oldPassword: this.passwordForm.oldpassword,
            newPassword: this.passwordForm.newpassword
          },
        ).then(res => {
          if (res.data.code === 200) {
            Message({
              message: '修改成功',
              type: 'success',
              customClass: 'message-global'
            });
            this.passwordForm.oldpassword = '';
            this.passwordForm.newpassword = '';
            this.passwordForm.confirmpassword = '';
            this.passwordForm.inputAccess = false;
            this.isEditing.password = false;
            this.verifyCode = '';
          } else {
            Message({
              message: res.data.msg,
              type: 'error',
              customClass: 'message-global'
            });
          }
        }).catch(err => {
          Message(
            {
              message: err,
              type: 'error',
              customClass: 'message-global'
            }
          );
        });
      }
    },
    cancelPassword() {
      this.passwordForm.verifycode = '';
      this.passwordForm.oldpassword = '';
      this.passwordForm.newpassword = '';
      this.passwordForm.confirmpassword = '';
      this.passwordForm.inputAccess = false;
      this.isEditing.password = false;
    },
    handleClose(tag) {
      this.temp.tags.splice(this.temp.tags.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.temp.tags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    }
  },
  components: {
    MainHeader,
  },
  mounted() {

  }
}
</script>

<style scoped>
.main {
  height: 100%;
  width: 100%;
}

.profile-edit {
  text-align: center;
  height: 100%;
}

.profile-edit-main {
  position: relative;
  display: inline-block;
  width: 100%;
  min-width: 1000px;
  box-shadow: 3px 3px 3px 3px #888888;
  margin-top: 20px;
  text-align: left;
  border-radius: 4px;
  margin-bottom: 20px;
  background-color: rgba(255, 255, 255, 0.8);
}

img {
  width: 180px;
  height: 180px;
  Object-fit: cover;
}

.profile-edit-avatar {
  position: absolute;
  top: 20px;
  margin-left: 20px;
  display: inline-block;
  width: 180px;
  height: 180px;
  margin-top: 10px;
}

.profile-edit-text {
  position: relative;
  left: 230px;
  top: 10px;
  display: inline-block;
  margin-left: 10px;
  margin-bottom: 30px;
  width: 75%;
  border-radius: 5px;
  margin-top: 10px;
}

.profile-edit-text-basic {
  min-height: 750px;
}

:deep .avatar-uploader .el-upload {
  border: 2px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 180px;
  height: 180px;
  transition: all 0.3s ease;
}

:deep .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  position: absolute;
  font-size: 28px;
  color: #a7b1bd9d;
  width: 180px;
  height: 180px;
  line-height: 180px;
  text-align: center;
  transition: all 0.3s ease;
  z-index: 1;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.avatar-uploader-icon:hover {
  color: #409EFF;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-divider {
  margin-top: 20px;
  margin-bottom: 20px;
}

.profile-edit-text-basic-item-title {
  display: inline-block;
  width: 100px;
  font-size: 18px;
  font-weight: 500;
  margin-left: 5px;
  margin-top: 10px;
  margin-bottom: 10px;
}

.el-tag+.el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;

}

.el-scrollbar {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

:deep .el-scrollbar__wrap {

  height: 100%;
  height: 100%;
  overflow: scroll;
  overflow-x: auto;
}

.edit-option {
  font-size: 17px;
  color: #409EFF;
  cursor: pointer;
}

.edit-option:hover {
  color: #0a67c4;
}
</style>

<style>
.message-global {
  z-index: 9999 !important;
}
</style>